'use strict'

import {app, BrowserWindow, ipcMain} from 'electron'
import moment from 'moment'

// 操++ Store must be imported for the shitty vuex-electron sharedMutations
import '../renderer/store'
/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */
/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
import {autoUpdater} from 'electron-updater'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow () {
  /**
     * Initial window options
     */
  mainWindow = new BrowserWindow({
    height: 1080,
    useContentSize: true,
    width: 1920,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true,
      webviewTag: true
    }
  })

  mainWindow.loadURL(winURL)
  // 禁用菜单
  mainWindow.setMenu(null)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
  let pathSep = require('path').sep
  let tmpPath = app.getPath('temp') + 'invoice' + pathSep
  console.log(tmpPath)
  mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
    if (item.getFilename().indexOf('.pdf') > 0) {
      let path = tmpPath + moment().format('YYYYMMDD') + pathSep + item.getFilename()
      item.setSavePath(path)
      item.on('updated', (event, state) => {
        if (state === 'interrupted') {
          console.log('Download is interrupted but can be resumed')
        } else if (state === 'progressing') {
          if (item.isPaused()) {
            console.log('Download is paused')
          } else {
            console.log(`Received bytes: ${item.getReceivedBytes()}`)
          }
        }
      })
      item.once('done', (event, state) => {
        if (state === 'completed') {
          console.log('Download successfully')
          // 回显 调用渲染进程方法
          mainWindow.webContents.send('invoice-downloaded', path)
        } else {
          console.log(`Download failed: ${state}`)
          // 回显 调用渲染进程方法
          mainWindow.webContents.send('invoice-download-failed', path)
        }
      })
    }
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
ipcMain.on('getPrinterList', (event) => {
  // 主线程获取打印机列表
  const list = mainWindow.webContents.getPrinters()
  // 通过webContents发送事件到渲染线程，同时将打印机列表也传过去
  mainWindow.webContents.send('getPrinterList', list)
})

// 监听检查更新指令
ipcMain.on('checkForUpdate', () => {
  // 执行更新检查
  if (process.env.NODE_ENV === 'production') {
    autoUpdater.checkForUpdatesAndNotify()
  }
})

// 关闭程序执行更新
ipcMain.on('exit-and-update', () => {
  autoUpdater.quitAndInstall()
})

function sendStatusToWindow (text) {
  mainWindow.webContents.send('message', text)
}

autoUpdater.on('checking-for-update', () => {
  sendStatusToWindow('正在检查更新')
})
autoUpdater.on('update-available', (info) => {
  sendStatusToWindow('有可用的更新')
})
autoUpdater.on('update-not-available', (info) => {
  sendStatusToWindow('已是最新版本')
})
autoUpdater.on('error', (err) => {
  console.log(err)
  sendStatusToWindow('更新出错')
})
autoUpdater.on('download-progress', (progressObj) => {
  sendStatusToWindow('下载更新:' + parseInt(progressObj.percent) + '%')
})
autoUpdater.on('update-downloaded', (info) => {
  sendStatusToWindow('重启程序更新')
})

// 下载pdf文件
ipcMain.on('download-invoice', (evt, url) => {
  mainWindow.webContents.downloadURL(url)
})
